const express = require('express');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, notFound, forbidden, asyncHandler, paginated } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');

// 导入服务层
const notificationService = require('../services/notificationService');

/**
 * 获取消息列表
 * GET /notifications
 */
router.get('/', authenticateToken, asyncHandler(async (req, res) => {
  const { page, limit } = validatePagination(req.query);
  const { type, status } = req.query;
  const userId = req.user.id;

  // 验证消息类型
  if (type) {
    const typeValidation = validateEnum(type, ['system', 'course', 'activity', 'achievement'], '消息类型');
    if (!typeValidation.isValid) {
      return badRequest(res, typeValidation.message);
    }
  }

  // 验证状态
  if (status) {
    const statusValidation = validateEnum(status, ['read', 'unread'], '消息状态');
    if (!statusValidation.isValid) {
      return badRequest(res, statusValidation.message);
    }
  }

  const options = {
    page,
    limit,
    type,
    status,
    user_id: userId
  };

  const result = await systemDao.getUserNotifications(options);

  const formattedList = result.notifications.map(notification => ({
    id: notification.id,
    title: notification.title,
    content: notification.content,
    type: notification.type,
    status: notification.status,
    createdAt: notification.created_at,
    readAt: notification.read_at,
    extra: notification.extra_data ? JSON.parse(notification.extra_data) : null
  }));

  // 获取未读消息数量
  const unreadCount = await systemDao.getUnreadNotificationCount(userId);

  paginated(res, formattedList, result.total, page, limit, { unreadCount });
}));

/**
 * 标记消息已读
 * PUT /notifications/:id/read
 */
router.put('/:id/read', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的消息ID');
  }

  const notificationId = parseInt(id);
  
  // 检查消息是否存在且属于当前用户
  const notification = await systemDao.getNotificationById(notificationId);
  if (!notification) {
    return notFound(res, '消息不存在');
  }

  if (notification.user_id !== userId) {
    return forbidden(res, '无权操作此消息');
  }

  if (notification.status === 'read') {
    return badRequest(res, '消息已经是已读状态');
  }

  // 标记为已读
  await systemDao.markNotificationAsRead(notificationId);

  success(res, null, '标记成功');
}));

/**
 * 批量标记消息已读
 * PUT /notifications/batch-read
 */
router.put('/batch-read', authenticateToken, asyncHandler(async (req, res) => {
  const { ids } = req.body;
  const userId = req.user.id;

  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    return badRequest(res, '请提供要标记的消息ID列表');
  }

  // 验证所有ID都是有效的数字
  const invalidIds = ids.filter(id => isNaN(parseInt(id)));
  if (invalidIds.length > 0) {
    return badRequest(res, '包含无效的消息ID');
  }

  const notificationIds = ids.map(id => parseInt(id));

  // 批量标记为已读
  const updatedCount = await systemDao.batchMarkNotificationsAsRead(userId, notificationIds);

  success(res, { updatedCount }, `成功标记 ${updatedCount} 条消息为已读`);
}));

/**
 * 标记所有消息已读
 * PUT /notifications/read-all
 */
router.put('/read-all', authenticateToken, asyncHandler(async (req, res) => {
  const userId = req.user.id;

  const updatedCount = await systemDao.markAllNotificationsAsRead(userId);

  success(res, { updatedCount }, `成功标记 ${updatedCount} 条消息为已读`);
}));

/**
 * 删除消息
 * DELETE /notifications/:id
 */
router.delete('/:id', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id;
  
  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的消息ID');
  }

  const notificationId = parseInt(id);
  
  // 检查消息是否存在且属于当前用户
  const notification = await systemDao.getNotificationById(notificationId);
  if (!notification) {
    return notFound(res, '消息不存在');
  }

  if (notification.user_id !== userId) {
    return forbidden(res, '无权删除此消息');
  }

  // 删除消息
  await systemDao.deleteNotification(notificationId);

  success(res, null, '删除成功');
}));

/**
 * 批量删除消息
 * DELETE /notifications/batch
 */
router.delete('/batch', authenticateToken, asyncHandler(async (req, res) => {
  const { ids } = req.body;
  const userId = req.user.id;

  if (!ids || !Array.isArray(ids) || ids.length === 0) {
    return badRequest(res, '请提供要删除的消息ID列表');
  }

  // 验证所有ID都是有效的数字
  const invalidIds = ids.filter(id => isNaN(parseInt(id)));
  if (invalidIds.length > 0) {
    return badRequest(res, '包含无效的消息ID');
  }

  const notificationIds = ids.map(id => parseInt(id));

  // 批量删除
  const deletedCount = await systemDao.batchDeleteNotifications(userId, notificationIds);

  success(res, { deletedCount }, `成功删除 ${deletedCount} 条消息`);
}));

/**
 * 获取消息统计
 * GET /notifications/statistics
 */
router.get('/statistics', authenticateToken, asyncHandler(async (req, res) => {
  const userId = req.user.id;

  const statistics = await systemDao.getNotificationStatistics(userId);

  success(res, statistics);
}));

/**
 * 获取消息设置
 * GET /notifications/settings
 */
router.get('/settings', authenticateToken, asyncHandler(async (req, res) => {
  const userId = req.user.id;

  // 这里可以从用户设置表获取通知偏好设置
  // 现在返回默认设置
  const settings = {
    systemNotifications: true,
    courseNotifications: true,
    activityNotifications: true,
    achievementNotifications: true,
    emailNotifications: false,
    pushNotifications: true,
    quietHours: {
      enabled: false,
      startTime: '22:00',
      endTime: '08:00'
    }
  };

  success(res, settings);
}));

/**
 * 更新消息设置
 * PUT /notifications/settings
 */
router.put('/settings', authenticateToken, asyncHandler(async (req, res) => {
  const userId = req.user.id;
  const {
    systemNotifications,
    courseNotifications,
    activityNotifications,
    achievementNotifications,
    emailNotifications,
    pushNotifications,
    quietHours
  } = req.body;

  // 验证设置数据
  const settings = {};
  
  if (systemNotifications !== undefined) {
    settings.systemNotifications = Boolean(systemNotifications);
  }
  
  if (courseNotifications !== undefined) {
    settings.courseNotifications = Boolean(courseNotifications);
  }
  
  if (activityNotifications !== undefined) {
    settings.activityNotifications = Boolean(activityNotifications);
  }
  
  if (achievementNotifications !== undefined) {
    settings.achievementNotifications = Boolean(achievementNotifications);
  }
  
  if (emailNotifications !== undefined) {
    settings.emailNotifications = Boolean(emailNotifications);
  }
  
  if (pushNotifications !== undefined) {
    settings.pushNotifications = Boolean(pushNotifications);
  }

  if (quietHours) {
    settings.quietHours = {
      enabled: Boolean(quietHours.enabled),
      startTime: quietHours.startTime || '22:00',
      endTime: quietHours.endTime || '08:00'
    };
  }

  // TODO: 这里应该保存到用户设置表
  // await userDao.updateNotificationSettings(userId, settings);

  success(res, settings, '设置更新成功');
}));

/**
 * 创建系统通知（管理员接口）
 * POST /notifications/system
 */
router.post('/system', authenticateToken, asyncHandler(async (req, res) => {
  const { title, content, type = 'system', targetUsers, extraData } = req.body;
  
  // 这里应该检查用户是否有管理员权限
  // 现在简单返回错误
  return forbidden(res, '无权限创建系统通知');

  // 参数验证
  if (!title || !content) {
    return badRequest(res, '标题和内容不能为空');
  }

  // 验证消息类型
  const typeValidation = validateEnum(type, ['system', 'course', 'activity', 'achievement'], '消息类型');
  if (!typeValidation.isValid) {
    return badRequest(res, typeValidation.message);
  }

  // 创建通知
  const notificationData = {
    title,
    content,
    type,
    extra_data: extraData ? JSON.stringify(extraData) : null
  };

  // 如果指定了目标用户，为每个用户创建通知
  if (targetUsers && Array.isArray(targetUsers)) {
    const notifications = await systemDao.createBulkNotifications(notificationData, targetUsers);
    success(res, { count: notifications.length }, '系统通知创建成功');
  } else {
    // 为所有用户创建通知
    const notifications = await systemDao.createNotificationForAllUsers(notificationData);
    success(res, { count: notifications.length }, '系统通知创建成功');
  }
}));

module.exports = router;
